/**
 * Created by xinxinran on 2018/7/13.
 */
'use strict';

import axios from 'axios';
import store from '../store'

const apiCallHandler = (callPromise, option) => {
    option = option || {throwError: true};

    return callPromise.then(resp => {
        if (resp.status === 200) {
            let respData = resp.data;
            if (respData && respData.status === 'SUCCESS') {
                return respData;
            }
        }

        resp.data = resp.data || {status: 'ERROR', message: `status code is : ${resp.status}`};
        throw resp;
    }).catch(err => {
        if (err.status === 401) {
            store.commit('changeRoute', {path: '/login'});
            return;
        }

        if (option.throwError) {
            throw err;
        } else {
            return err;
        }
    });
};

export default {
    get: (url, option) => apiCallHandler(axios.get(url), option),
    post: (url, data, option) => apiCallHandler(axios.post(url, data), option),
    put: (url, data, option) => apiCallHandler(axios.put(url, data), option),
    del: (url, option) => apiCallHandler(axios.delete(url), option)
};
